import logging

import routes
from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to
from pylons.decorators import validate

from cibynet.lib.base import *
from cibynet.lib.auth import authorisation
from cibynet.model.m_feedbacks import FeedbackValidator

log = logging.getLogger(__name__)


class FeedbacksController(BaseController):
  """REST Controller styled on the Atom Publishing Protocol"""

  def __before__(self, environ):
    """The user must be authenticated to give his feedback.
    """
    if not authorisation.UserIsAuthenticated():
      abort(401)
    
  @authorisation.UserInGroupD("admin")
  def index(self, format='html'):
    """GET /feedbacks: All items in the collection."""
    fq = meta.Session.query(Feedback).order_by(Feedback.id.desc())
    c.feedbacks_q = fq
    return render("/feedbacks/index.mako")

  @validate(schema=FeedbackValidator(), form='new', state=c, 
        auto_insert_errors=True)
  def create(self, environ):
    """POST /feedbacks: Create a new item."""
    url = self.form_result['url']
    comment = self.form_result['comment']
    user = environ.get("REMOTE_USER_OBJ")
    f = Feedback(url, comment, user)
    meta.Session.add(f)
    meta.Session.commit()
    routes.redirect_to(str(url))

  def new(self, environ, format='html'):
    """GET /feedbacks/new: Form to create a new item."""
    # TODO: use referer also
    path_info = environ['PATH_INFO']
    url = "/"
    if path_info.endswith(g.FEEDBACK_PART):
      url = path_info[:0-len(g.FEEDBACK_PART)]
      # we only alow feedback of one feedback page, not more recursion!
      if url.endswith("/%s%s" % ((g.FEEDBACK_PART,) * 2)):
        routes.redirect_to(url)
        # We don't want to abort here...
        # abort(404)
    c.url = url
    return render("feedbacks/new.mako")

  @authorisation.UserInGroupD("admin")
  def update(self, id):
    """PUT /feedbacks/id: Update an existing item."""
    pass

  @authorisation.UserInGroupD("admin")
  def delete(self, id):
    """DELETE /feedbacks/id: Delete an existing item."""
    pass

  @authorisation.UserInGroupD("admin")
  def show(self, id, format='html'):
    """GET /feedbacks/id: Show a specific item."""
    pass

  @authorisation.UserInGroupD("admin")
  def edit(self, id, format='html'):
    """GET /feedbacks/id/edit: Form to edit an existing item."""
    pass
